<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/17
 * Time: 14:28
 */

namespace common\rest\actions\auth;

use common\models\c2\entity\FeUserProfile;
use Yii;
use yii\base\Model;
use yii\db\ActiveRecord;
use yii\web\ServerErrorHttpException;
use yii\rest\Action;
use common\rest\statics\ResponseDatum;
use common\rest\base\WxException;
use common\rest\statics\OperationResult;

class ProfileSaveAction extends Action{
    /**
     * @var string the scenario to be assigned to the profileModel before it is validated and updated.
     */
    public $scenario = Model::SCENARIO_DEFAULT;

    public $authIdAttribute = 'user_id';

    public $view = 'edit';

    public function run($id){
        try{
            if ($this->checkAccess) {
                call_user_func($this->checkAccess, $this->id);
            }
            $params = Yii::$app->getRequest()->getBodyParams();
            $modelClass = $this->modelClass;
            if(empty($id)){
                throw new WxException(Yii::t('app.c2', "Missing parameter：{s1}", ['s1' => 'id']), OperationResult::ERROR_600, null, []);
            }
            $model = $modelClass::findOne([
                'id' => $id,
                $this->authIdAttribute => Yii::$app->user->id,
            ]);
            $profileModel = $model->profile;
            if (is_null($model) && is_null($profileModel)) {
                throw new WxException(Yii::t('app.rest', 'Resource not found!'), OperationResult::ERROR_404, $params, null);
            }
            if($profileModel->load($params,'FeUserProfile')){
                if ($profileModel->save()) {
                    return ResponseDatum::getSuccessDatum(['msg' => Yii::t('app.c2', 'Operation completed successfully!')], $profileModel);
                } elseif(!$profileModel->hasErrors()) {
                    Yii::$app->session->setFlash($profileModel->getMessageName(), $profileModel->errors);
                }
            }else{
                return ResponseDatum::getErrorDatum([
                    'code' =>OperationResult::ERROR_600,
                    'msg' => Yii::t('app.c2', 'Params is not load!')
                ]);
            }
        }catch(WxException $ex){
            return ResponseDatum::getErrorDatum([
                'code' => $ex->getCode(),
                'msg' => $ex->getMessage(),
                'extraData' => $ex->extraData,
            ], $ex->data);
        }
    }

}